from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
counties["features"][0]
{'type': 'Feature',
'properties': {'GEO_ID': '0500000US01001',
'STATE': '01',
'COUNTY': '001',
'NAME': 'Autauga',
'LSAD': 'County',
'CENSUSAREA': 594.436},
'geometry': {'type': 'Polygon',
'coordinates': [[[-86.496774, 32.344437],
[-86.717897, 32.402814],
[-86.814912, 32.340803],
[-86.890581, 32.502974],
[-86.917595, 32.664169],
[-86.71339, 32.661732],
[-86.714219, 32.705694],
[-86.413116, 32.707386],
[-86.411172, 32.409937],
[-86.496774, 32.344437]]]},
'id': '01001'}
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
df.head()
| fips | unemp | |
|---|---|---|
| 0 | 01001 | 5.3 |
| 1 | 01003 | 5.4 |
| 2 | 01005 | 8.6 |
| 3 | 01007 | 6.6 |
| 4 | 01009 | 5.5 |
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
import plotly.express as px
df = px.data.election()
geojson = px.data.election_geojson()
fig = px.choropleth(df, geojson=geojson, color="Bergeron",
locations="district", featureidkey="properties.district",
projection="mercator"
)
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
import plotly.express as px
df = px.data.election()
geojson = px.data.election_geojson()
fig = px.choropleth(df, geojson=geojson, color="winner",
locations="district", featureidkey="properties.district",
projection="mercator", hover_data=["Bergeron", "Coderre", "Joly"]
)
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
import plotly.express as px
import geopandas as gpd
df = px.data.election()
geo_df = gpd.GeoDataFrame.from_features(
px.data.election_geojson()["features"]
).merge(df, on="district").set_index("district")
fig = px.choropleth(geo_df,
geojson=geo_df.geometry,
locations=geo_df.index,
color="Joly",
projection="mercator")
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
--------------------------------------------------------------------------- OSError Traceback (most recent call last) /var/folders/tt/hzn__v4945bfpj662bgrkr4h0000gn/T/ipykernel_45845/1092348108.py in <module> 1 import plotly.express as px ----> 2 import geopandas as gpd 3 4 df = px.data.election() 5 geo_df = gpd.GeoDataFrame.from_features( /usr/local/anaconda3/envs/plotly/lib/python3.8/site-packages/geopandas/__init__.py in <module> ----> 1 from geopandas.geoseries import GeoSeries # noqa 2 from geopandas.geodataframe import GeoDataFrame # noqa 3 from geopandas.array import _points_from_xy as points_from_xy # noqa 4 5 from geopandas.io.file import read_file # noqa /usr/local/anaconda3/envs/plotly/lib/python3.8/site-packages/geopandas/geoseries.py in <module> 10 11 import pyproj ---> 12 from shapely.geometry.base import BaseGeometry 13 from shapely.ops import transform 14 /usr/local/anaconda3/envs/plotly/lib/python3.8/site-packages/shapely/geometry/__init__.py in <module> 2 """ 3 ----> 4 from .base import CAP_STYLE, JOIN_STYLE 5 from .geo import box, shape, asShape, mapping 6 from .point import Point, asPoint /usr/local/anaconda3/envs/plotly/lib/python3.8/site-packages/shapely/geometry/base.py in <module> 15 16 from shapely.affinity import affine_transform ---> 17 from shapely.coords import CoordinateSequence 18 from shapely.errors import WKBReadingError, WKTReadingError 19 from shapely.ftools import wraps /usr/local/anaconda3/envs/plotly/lib/python3.8/site-packages/shapely/coords.py in <module> 6 from ctypes import byref, c_double, c_uint 7 ----> 8 from shapely.geos import lgeos 9 from shapely.topology import Validating 10 /usr/local/anaconda3/envs/plotly/lib/python3.8/site-packages/shapely/geos.py in <module> 111 _lgeos = load_dll('geos_c', fallbacks=alt_paths) 112 --> 113 free = load_dll('c').free 114 free.argtypes = [c_void_p] 115 free.restype = None /usr/local/anaconda3/envs/plotly/lib/python3.8/site-packages/shapely/geos.py in load_dll(libname, fallbacks, mode) 52 else: 53 # No shared library was loaded. Raise OSError. ---> 54 raise OSError( 55 "Could not find lib {0} or load any of its variants {1}.".format( 56 libname, fallbacks or [])) OSError: Could not find lib c or load any of its variants [].
import plotly.express as px
df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, locations="iso_alpha",
color="lifeExp", # lifeExp is a column of gapminder
hover_name="country", # column to add to hover information
color_continuous_scale=px.colors.sequential.Plasma)
fig.show()
import plotly.express as px
fig = px.choropleth(locations=["CA", "TX", "NY"], locationmode="USA-states", color=[1,2,3], scope="usa")
fig.show()
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
fig = go.Figure(data=go.Choropleth(
locations=df['code'], # Spatial coordinates
z = df['total exports'].astype(float), # Data to be color-coded
locationmode = 'USA-states', # set of locations match entries in `locations`
colorscale = 'Reds',
colorbar_title = "Millions USD",
))
fig.update_layout(
title_text = '2011 US Agriculture Exports by State',
geo_scope='usa', # limite map scope to USA
)
fig.show()
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
for col in df.columns:
df[col] = df[col].astype(str)
df['text'] = df['state'] + '<br>' + \
'Beef ' + df['beef'] + ' Dairy ' + df['dairy'] + '<br>' + \
'Fruits ' + df['total fruits'] + ' Veggies ' + df['total veggies'] + '<br>' + \
'Wheat ' + df['wheat'] + ' Corn ' + df['corn']
fig = go.Figure(data=go.Choropleth(
locations=df['code'],
z=df['total exports'].astype(float),
locationmode='USA-states',
colorscale='Reds',
autocolorscale=False,
text=df['text'], # hover text
marker_line_color='white', # line markers between states
colorbar_title="Millions USD"
))
fig.update_layout(
title_text='2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True, # lakes
lakecolor='rgb(255, 255, 255)'),
)
fig.show()
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = 'Blues',
autocolorscale=False,
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '$',
colorbar_title = 'GDP<br>Billions US$',
))
fig.update_layout(
title_text='2014 Global GDP',
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
annotations = [dict(
x=0.55,
y=0.1,
xref='paper',
yref='paper',
text='Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
showarrow = False
)]
)
fig.show()
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv')
df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(lambda x: str(x).zfill(2))
df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(lambda x: str(x).zfill(3))
df_sample['FIPS'] = df_sample['State FIPS Code'] + df_sample['County FIPS Code']
colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef", "#b3d2e9", "#9ecae1",
"#85bcdb", "#6baed6", "#57a0ce", "#4292c6", "#3082be", "#2171b5", "#1361a9",
"#08519c", "#0b4083", "#08306b"
]
endpts = list(np.linspace(1, 12, len(colorscale) - 1))
fips = df_sample['FIPS'].tolist()
values = df_sample['Unemployment Rate (%)'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=endpts, colorscale=colorscale,
show_state_data=False,
show_hover=True,
asp = 2.9,
title_text = 'USA by Unemployment %',
legend_title = '% unemployed'
)
fig.layout.template = None
fig.show()